<template>
  <AuFormModal
    ref="formModalRef"
    v-model="showModal"
    :title="title"
    :formList="formList"
    :formData="selfFormData"
    :modalProps="{
      width: 600
    }"
    :formProps="{
      class: '!w-[386px]'
    }"
    @handleConfirm="handleConfirm"
  />
</template>

<script setup lang="ts">
import { AuFormModal } from "@/components/AuModal";
import { computed, getCurrentInstance, onMounted, ref, watch } from "vue";
import { businessGetList } from "@/api/factory/business";
import { deviceActivation, DeviceEnterProp } from "@/api/factory/device";
import { cloneDeep } from "lodash-unified";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

interface Props {
  modelValue: boolean;
  formData: DeviceEnterProp[];
}

const props = defineProps<Props>();
const { proxy } = getCurrentInstance();
const { t } = useI18n();

const emits = defineEmits(["update:modelValue", "confirm"]);
const title = ref();
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emits("update:modelValue", value);
  }
});

const formList = ref([
  {
    type: "select",
    key: "business_val",
    label: t("device_manage.distribution.title"),
    placeholder: t("device_manage.distribution.placeholder"),
    valueKey: "id",
    labelKey: "brand",
    options: [],
    style: {
      width: "294px"
    }
  }
]);
const selfFormData = ref({});
const businessList = ref([]);
const formModalRef = ref();

const handleConfirm = async (data: { business_val: string }) => {
  const { business_val } = data;
  if (!business_val) {
    ElMessage.error(t("device_manage.distribution.error"));
    return;
  }
  let devHasAcList = "";
  let devNoAcStr = "";
  const devNoAcList = [];

  for (const item of props.formData) {
    if (item.is_activation === 1) {
      // devHasAcList += `${item.device_id}${item.device?.business_name ? t("device_manage.distribution.assigned_to") + item.device?.business_name : ""},`;
      devHasAcList += `${item.device_id}、`;
    } else {
      devNoAcList.push(item);
      devNoAcStr += `${item.device_id}, `;
    }
  }
  if (!devNoAcList.length) {
    await proxy.$auMessageBox.alert(
      `${t("device_manage.distribution.alert_message")}`,
      t("notice.title")
    );
    return;
  }
  if (devHasAcList) {
    await proxy.$auMessageBox.confirm(
      // `${devNoAcStr.slice(0, -1)}${t("device_manage.distribution.has_assigned")}, ${t("device_manage.distribution.confirm_message")}`,
      // 已分配设备（ATT-U4303291102、ATT-KBT040809、ATT-KBT040808、ATT-KBT040807）已过滤，是否继续将剩余设备分配给该商家？请确认。
      t("device_manage.distribution.has_assigned", {
        device: devHasAcList.slice(0, -1)
      }),
      t("notice.title")
    );
  }
  const brand = businessList.value.find(
    item => item.id === business_val
  )?.brand;
  const fails = [];
  for (const item of devNoAcList) {
    try {
      const res = await deviceActivation({
        device_id: item.device_id,
        business_id: business_val,
        brand
      });
      if (res.code != 200) {
        fails.push(item.device_id);
      }
    } catch (e) {
      fails.push(item.device_id);
    }
  }
  // if (fails.length) {
  //   ElMessage.error(`${fails.join(",")}设备激活失败`);
  // }
  emits("update:modelValue", false);
  emits("confirm");
};

watch(
  () => [props.modelValue, props.formData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as DeviceEnterProp[];
      title.value =
        rowData.length > 1
          ? t("device_manage.distribution.batch_title")
          : t("device_manage.distribution.title");

      businessGetList({ page: 1, size: 0 }).then(res => {
        businessList.value = res.data;
        formModalRef.value?.setFormProps("business_val", {
          options: res.data
        });
      });
    } else {
      formModalRef.value?.reset();
    }
  }
);
</script>
